use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::Read;
use anyhow::anyhow;
use serde_json::Value;
use   crate::utils::json_content::{ContextValues, JsonContext } ;
use  crate::utils ::string_utils::StringFileWrapper;
#[derive(Debug)]
pub enum JSONReturnType {
    Object(HashMap<String, Value>),
    Array(Vec<Value>),
    String(String),
    Number(f64),
    Integer(i64),
    Boolean(bool),
    Null,
}
pub struct JSONParser {

    pub  json_fd: Option<File>,           // 文件描述符
    pub json_str: StringFileWrapper,
    pub index: usize,
    pub context: JsonContext,
    pub logging: bool,
    pub logger: RefCell<Vec<HashMap<String, String>>>,
}

impl JSONParser {
    pub(crate) fn new<R: Read + Clone>(
        json_str: Option<String>,
        json_fd: Option<File >,
        logging: bool,
        json_fd_chunk_length: usize,
    )
        -> io::Result<Self>
    where  R : Read + Clone  {
        let json_str = if let Some(ref fd) = json_fd {
            StringFileWrapper::new(fd.clone(), json_fd_chunk_length)?
        } else {
            StringFileWrapper {
                content: json_str.unwrap_or_default(),
                index: 0,
            }
        };

        Ok(Self {
            json_fd,
            json_str,
            index: 0,
            context: JsonContext::default(),
            logging,
            logger: RefCell::new(Vec::new()),
        })
    }

    fn log(&self, message: &str) {
        if self.logging {
            let mut log_entry = HashMap::new();
            log_entry.insert("message".to_string(), message.to_string());
            self.logger.borrow_mut().push(log_entry);
        }
    }

   pub fn parse(&mut self) -> Result<JSONReturnType, anyhow::Error> {
        // 跳过空白字符
        while let Some(ch) = self.json_str.peek_char() {
            if ch.is_whitespace() {
                self.json_str.read_char();
            } else {
                break;
            }
        }

        // 根据第一个字符解析 JSON 值
        match self.json_str.peek_char() {
            Some('{') => self.parse_object(),
            Some('[') => self.parse_array(),
            Some('"') => self.parse_string(),
            Some('t') | Some('f') => self.parse_boolean(),
            Some('n') => self.parse_null(),
            Some(ch) if ch.is_digit(10) || ch == '-' => self.parse_number(),
            _ =>  {
                Err(anyhow!("Invalid JSON"))
            }
        }
    }

    fn parse_object(&mut self) -> Result<JSONReturnType, anyhow::Error> {
        let mut map = HashMap::new();
        self.json_str.read_char(); // 跳过 '{'

        while let Some(ch) = self.json_str.peek_char() {
            if ch == '}' {
                self.json_str.read_char(); // 跳过 '}'
                break;
            }

            // 解析键
            let key = self.parse_string()?;
            // 跳过 ':'
            while let Some(ch) = self.json_str.peek_char() {
                if ch.is_whitespace() || ch == ':' {
                    self.json_str.read_char();
                } else {
                    break;
                }
            }

            // 解析值
            let value = self.parse()?;
            if let JSONReturnType::String(key_str) = key {
                map.insert(key_str, self.json_value_to_serde_value(value));
            }

            // 跳过 ',' 或 '}'
            while let Some(ch) = self.json_str.peek_char() {
                if ch.is_whitespace() || ch == ',' {
                    self.json_str.read_char();
                } else {
                    break;
                }
            }
        }

        Ok(JSONReturnType::Object(map))
    }

    fn parse_array(&mut self) -> Result<JSONReturnType, anyhow::Error> {
        let mut vec = Vec::new();
        self.json_str.read_char(); // 跳过 '['

        while let Some(ch) = self.json_str.peek_char() {
            if ch == ']' {
                self.json_str.read_char(); // 跳过 ']'
                break;
            }

            // 解析值
            let value = self.parse()?;
            vec.push(self.json_value_to_serde_value(value));

            // 跳过 ',' 或 ']'
            while let Some(ch) = self.json_str.peek_char() {
                if ch.is_whitespace() || ch == ',' {
                    self.json_str.read_char();
                } else {
                    break;
                }
            }
        }

        Ok(JSONReturnType::Array(vec))
    }

    fn parse_string(&mut self) -> Result<JSONReturnType, anyhow::Error> {
        self.json_str.read_char(); // 跳过 '"'
        let mut s = String::new();

        while let Some(ch) = self.json_str.read_char() {
            if ch == '"' {
                break;
            }
            s.push(ch);
        }

        Ok(JSONReturnType::String(s))
    }

    fn parse_boolean(&mut self) -> Result<JSONReturnType, anyhow::Error> {
        let mut s = String::new();
        while let Some(ch) = self.json_str.read_char() {
            if ch.is_alphabetic() {
                s.push(ch);
            } else {
                break;
            }
        }

        match s.as_str() {
            "true" => Ok(JSONReturnType::Boolean(true)),
            "false" => Ok(JSONReturnType::Boolean(false)),
            _=> Err(anyhow!("Invalid boolean"))
        }
    }

    fn parse_null(&mut self) -> Result<JSONReturnType, anyhow::Error> {
        let mut s = String::new();
        while let Some(ch) = self.json_str.read_char() {
            if ch.is_alphabetic() {
                s.push(ch);
            } else {
                break;
            }
        }

        if s == "null" {
            Ok(JSONReturnType::Null)
        } else {
            Err (anyhow!("Invalid null"))
        }
    }

    fn parse_number(&mut self) -> Result<JSONReturnType, anyhow::Error> {
        let mut s = String::new();
        while let Some(ch) = self.json_str.read_char() {
            if ch.is_digit(10) || ch == '-' || ch == '.' || ch == 'e' || ch == 'E' {
                s.push(ch);
            } else {
                break;
            }
        }

        if let Ok(i) = s.parse::<i64>() {
            Ok(JSONReturnType::Integer(i))
        } else if let Ok(f) = s.parse::<f64>() {
            Ok(JSONReturnType::Number(f))
        } else {
             Err(anyhow::anyhow!("Invalid number"))
        }
    }

    fn json_value_to_serde_value(&self, value: JSONReturnType) -> Value {
        match value {
            JSONReturnType::Object(map) => {
                let mut serde_map = serde_json::Map::new();
                for (k, v) in map {
                    serde_map.insert(k, v);
                }
                Value::Object(serde_map)
            }
            JSONReturnType::Array(vec) => Value::Array(vec),
            JSONReturnType::String(s) => Value::String(s),
            JSONReturnType::Number(n) => Value::from(n),
            JSONReturnType::Integer(i) => Value::from(i),
            JSONReturnType::Boolean(b) => Value::from(b),
            JSONReturnType::Null => Value::Null,
        }
    }
}